package manage.modules.worker.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import manage.commons.Constants;
import manage.commons.cookie.UserState;
import manage.commons.cookie.UserStateSessionManager;
import manage.commons.utils.CookieUtils;
import manage.commons.utils.EncryptUtils;
import manage.modules.worker.model.WorkerInfo;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

public class WorkerLoginUtil {

	private static final List<String> URLS = new ArrayList<String>();
	private static final List<Long> SUPER_MANAGER = new ArrayList<Long>();

	static {
		URLS.add("/login/login-input.do");
		URLS.add("/login/login.jsp");
		URLS.add("/login.do");
		URLS.add("/main.jsp");
		URLS.add("/index.jsp");
		// super manager id
		SUPER_MANAGER.add(110l);
	}

	public static void login(WorkerInfo worker, HttpServletRequest request,
			HttpServletResponse response) {
		// 当前时间
		Long nowTime = System.currentTimeMillis();
		UserState userState = new UserState();
		userState.setUserId(worker.getWorkerId().intValue());
		userState.setPassword(worker.getPassword());
		userState.setLoginTime(nowTime);
		userState.setRemember(0);
		// 登录时判断是否是超级管理，如果是则在回话中加入一个标识
		if (isSuperManager(worker.getWorkerId())) {
			userState.setSuperManager(1);
		} else {
			userState.setSuperManager(0);
		}
		UserStateSessionManager sessionManager = new UserStateSessionManager(
				userState);
		String cookieString = sessionManager.toCookieString();

		int age = -1;
		if (userState.isRememberMe()) {
			age = 1 * 24 * 60 * 1000;// 记住1天
		}
		// 保存加密后的worker信息
		CookieUtils.addCookie(response, true, Constants.COOKIE_U, cookieString,
				age);

	}

	public static String forword(HttpServletRequest request) {
		if (URLS.contains(request.getRequestURI())) {
			return Constants.INDEX_ACTION;
		} else {
			String forward = request.getRequestURI();
			if (StringUtils.isNotEmpty(request.getQueryString())) {
				forward += "?" + request.getQueryString();
			}
			return forward;
		}
	}

	public static boolean isSuperManager(Long wokrerId) {
		if (null != wokrerId) {
			for (Long id : SUPER_MANAGER) {
				if (id.equals(wokrerId)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 取当前用户id，先到session，如果取不到再去cookie找
	 * 
	 * @param request
	 * @return
	 */
	public static Long getWorkerId(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Long currentWorkerId = (Long) session
				.getAttribute(Constants.SESSION_CURRENT_WORKER_ID);
		if (currentWorkerId == null || currentWorkerId <= 0) {
			currentWorkerId = NumberUtils.toLong((EncryptUtils
					.decrypt(CookieUtils.getCookie(request,
							Constants.COOKIE_WORKER_ID))));
		}
		return currentWorkerId;
	}
}
